package com.miage.kangourou.client.calendar;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.bradrydzewski.gwt.calendar.client.Appointment;
import com.bradrydzewski.gwt.calendar.client.AppointmentStyle;
import com.bradrydzewski.gwt.calendar.client.Calendar;
import com.bradrydzewski.gwt.calendar.client.CalendarSettings;
import com.bradrydzewski.gwt.calendar.client.CalendarSettings.Click;
import com.bradrydzewski.gwt.calendar.client.CalendarViews;
import com.bradrydzewski.gwt.calendar.client.event.DateRequestEvent;
import com.bradrydzewski.gwt.calendar.client.event.DateRequestHandler;
import com.bradrydzewski.gwt.calendar.client.event.DeleteEvent;
import com.bradrydzewski.gwt.calendar.client.event.DeleteHandler;
import com.bradrydzewski.gwt.calendar.client.event.UpdateEvent;
import com.bradrydzewski.gwt.calendar.client.event.UpdateHandler;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.logical.shared.OpenEvent;
import com.google.gwt.event.logical.shared.OpenHandler;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.DeferredCommand;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Widget;
import com.miage.kangourou.client.GetListesService;
import com.miage.kangourou.client.GetListesServiceAsync;
import com.miage.kangourou.client.beans.Evenement;

public class CalendarWidget extends GenericWidget {
	
	
	
	private final GetListesServiceAsync getListesService = GWT
	.create(GetListesService.class);
	private Calendar calendar = null;
	
private OpenHandler<Appointment> openHandler;
private UpdateHandler<Appointment> updateHandler;
	
	
	private CalendarSettings settings = null;
	public CalendarWidget(KangourouPanel context) {
		super(context, "calendar");
	}

	public Widget createWidget() {
		calendar = new Calendar();
		settings = new CalendarSettings();

		// change hour offset to false to facilitate google style
		settings.setOffsetHourLabels(false);
		settings.setTimeBlockClickNumber(Click.Double);
		settings.setEnableDragDrop(false);
		settings.setWorkingHourStart(8);
		settings.setWorkingHourEnd(20);
		
		calendar.setSettings(settings);
		calendar.setView(CalendarViews.DAY, 6);
		calendar.setSize("100%", "100%");

		// Set the default hour to 8am
		DeferredCommand.addCommand(new Command(){ 
			@Override 
			public void execute() { 
				calendar.scrollToHour(8); 
			} 
		});


		updateHandler= new UpdateHandler<Appointment>() {
			public void onUpdate(UpdateEvent<Appointment> event) {
				boolean commit = Window
				.confirm("Are you sure you want to update the appointment \"" + event.getTarget().getTitle() + "\"");
				if (!commit) {
					event.setCancelled(true);
					update();
					System.out.println("Cancelled Appointment update");
				}
				else
				{
					final AsyncCallback<Boolean> misAjour = new AsyncCallback<Boolean>() {

						@Override
						public void onFailure(Throwable caught) {
							Window.alert("Erreur lors de l'appel serveur "
									+ caught.getMessage());
							
						}
					@Override
						public void onSuccess(Boolean result) {
							if(!result){
						Window.alert("Vous n'etes pas ADMIN");
							}
						update();
							
								
						}
					};
					
					getListesService.updateEventDate(Integer.valueOf(event.getTarget().getId()), event.getTarget().getStart(),event.getTarget().getEnd(),context.utilisateurEnCours, misAjour);
					
					
					
				}
			}
		};
		calendar.addUpdateHandler(updateHandler) ;

		/*
		calendar.addDateRequestHandler(new DateRequestHandler<Date>(){
			@Override
			public void onDateRequested(DateRequestEvent<Date> event) {
				Window.alert("requested: " + event.getTarget() + " " + ((Element)event.getClicked()).getInnerText());
			}
		});
		*/
		
		return calendar;
	}
	
	public Calendar getCalendar() {
		return calendar;
	}

	public CalendarSettings getSettings() {
		return settings;
	}

	public void configureWidget() {
		context.clickChangeDateButton(0);
		
		
		
		if(context.utilisateurEnCours.isAdmin()) {
		openHandler = new OpenHandler<Appointment>(){
			@Override
			public void onOpen(OpenEvent<Appointment> event) {
				PopupActionEvent popup = new PopupActionEvent();
				popup.show(event.getTarget(),context);
			}
		};
		calendar.addOpenHandler(openHandler);
		
		settings.setEnableDragDrop(true);
		}
		
		
		else {
			settings.setEnableDragDrop(false);
			settings.setEnableDragDrop(true);
			updateHandler= new UpdateHandler<Appointment>() {
				public void onUpdate(UpdateEvent<Appointment> event) {
				}
			};
			calendar.addUpdateHandler(updateHandler) ;

			
					
					openHandler = new OpenHandler<Appointment>(){
				@Override
				public void onOpen(OpenEvent<Appointment> event) {
				
				}
			};
			calendar.addOpenHandler(openHandler);
			
		}
		
	}
	
	public List<AppointmentStyle> getCalendarsStyles() {
		
		List<AppointmentStyle> appointmentsStyles = new ArrayList<AppointmentStyle>();
		List<Appointment> appointments = calendar.getAppointments();
		Appointment appt;
		
		for (int i = 0 ; i<appointments.size() ; ++i)
		{
			appt = (Appointment) appointments.get(i);
			
			if (appointmentsStyles.contains(appt.getStyle()) == false) {
				appointmentsStyles.add(appt.getStyle());
			}
		}
		
		return appointmentsStyles;
	}


	public void update(){
		
		final AsyncCallback<List<Evenement>> evenements = new AsyncCallback<List<Evenement>>() {

			@Override
			public void onFailure(Throwable caught) {
				Window.alert("Erreur lors de l'appel serveur "
						+ caught.getMessage());
			}
			@Override
			public void onSuccess(List<Evenement> result) {
				
				calendar.clearAppointments();
				for (Evenement e : result)
				{
				calendar.addAppointment((Appointment)e);
				}
				calendar.doLayout();
				
			}
		};
		
		int idGroupe =((RechercheMultiCritereWidget)context.getWidget("admin")).getGroupeSelected();
		int idEnseignant =((RechercheMultiCritereWidget)context.getWidget("admin")).getEnseignantSelected();
		int idSalle =((RechercheMultiCritereWidget)context.getWidget("admin")).getSalleSelected();
		int idMatiere =((RechercheMultiCritereWidget)context.getWidget("admin")).getMatiereSelected();
		
		Date dateDebutSemaine = calendar.getDate();
		Date dateFinSemaine = Util.addDays(dateDebutSemaine, 6);
		
		System.out.println("Recuperation des evenements entre le "+dateDebutSemaine+" et le "+dateFinSemaine + "\n Et avec les critere : " + idGroupe+ idEnseignant+ idSalle+ idMatiere );

		getListesService.getEvenementBetweenTwoDateAndCriteria(idGroupe, idEnseignant, idSalle, idMatiere, dateDebutSemaine, dateFinSemaine, evenements);
		
	}

	public void refreshAfterLogin() {
		
		
		
	}
	public void refreshAfterLogout() {
		
		
		
	}


}
